﻿using HungryCrowdLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HungryCrowd.HelperFunctions;
using System.Web.Script.Serialization;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;

namespace HungryCrowd.trader
{
    public partial class update : System.Web.UI.Page
    {
        #region Properties

        private HungryCrowdLibrary.ModelDto.Trader trader;
        public HungryCrowdLibrary.ModelDto.Trader Trader { get { return trader ?? new HungryCrowdLibrary.ModelDto.Trader(); } set { trader = value; } }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            ddlLocation.PopulateDropDownLists(typeof(Location));
            ddlMarkets.PopulateDropDownLists(typeof(Market));
            ddlCategories.PopulateDropDownLists(typeof(Category));
        }


        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            Trader = new HungryCrowdLibrary.ModelDto.Trader();
            Trader.Name = txtName.Text;
            Trader.ContactPerson = txtContactPerson.Text;
            Trader.ContactNumber = txtNumber.Text;
            Trader.TradingDays = txtTradingDays.Text;
            Trader.TradingArea = hdArea.Value;
            Trader.TradingYears = txtYears.Text;
            Trader.TradingHours = txtHours.Text;
            Trader.EmailAddress = txtEmail.Text;
            Trader.Description = txtDescription.Text;
            Trader.CategoryId = int.Parse(hdCategoryId.Value);
            Trader.MarketId = int.Parse(hdMarketId.Value);
            Trader.ImageUrl = SaveImage().Replace('\\', '/');
            Trader.IsActive = true;
            hdHiddenField.Value = new JavaScriptSerializer().Serialize(Trader);
        }

        private string SaveImage()
        {
            var path = string.Empty;
            var imageURL = string.Empty;

            if (fluProfilePic.HasFile)
            {
                path = ConfigurationManager.AppSettings["profilePicPath"];
                
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                path = string.Format("{0}{1}", ConfigurationManager.AppSettings["profilePicPath"], fluProfilePic.FileName); 
                File.WriteAllBytes(path, fluProfilePic.FileBytes);
                //SaveImageOnFTP(path);
                imageURL = string.Format("{0}images/traders/{1}", ConfigurationManager.AppSettings["imageURL"],fluProfilePic.FileName); //string.Format("{0}{1}", ConfigurationManager.AppSettings["imageURL"], path.Substring(path.IndexOf("images"), path.Length - path.IndexOf("images")));
                

            }
            return string.IsNullOrWhiteSpace(imageURL) ? "no file saved" : imageURL;
        }

        protected void SaveImageOnFTP(string filePath)
        {
            var request = (FtpWebRequest)WebRequest.Create("ftp://www.hungrycrowd.co.za/wwwroot/images/traders");
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential("thoorib", "rmQrShFQULrwRNu");

            // Copy the contents of the file to the request stream.
            StreamReader sourceStream = new StreamReader(filePath);
            byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            sourceStream.Close();
            request.ContentLength = fileContents.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            response.Close();
        
        }

    }
}